package com.bto.solar.work.service;

import com.bto.solar.work.common.BizException;
import com.bto.solar.work.constant.BizCode;
import com.bto.solar.work.constant.DBConstants;
import com.bto.solar.work.dao.IRoleService;
import com.bto.solar.work.entity.Role;
import com.bto.solar.work.entity.User;
import com.bto.solar.work.utils.JsonToListUtils;
import com.bto.solar.work.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BtoRolesService {

    @Autowired
    private IRoleService roleService;
    @Autowired
    @Lazy
    private BtoUserService btoUserService;
//
//    @Autowired
//    private RolesMapper rolesMapper;
//
//    @Autowired
//    private CompaniesMapper companiesMapper;
//
//    @Autowired
//    private RoleHasMenusMapper roleHasMenusMapper;
//
//    @Autowired
//    private PermissionsMapper permissionsMapper;
//
//    @Autowired
//    private MenusMapper menusMapper;
//
//    @Autowired
//    private RoleHasPermissionsMapper roleHasPermissionsMapper;
//
//    @Autowired
//    private RoleHasMenusPermissionsMapper roleHasMenusPermissionsMapper;
//
//    @Autowired
//    private IRolesService rolesService;
//
//
//    /**
//     * 查询部门管理的数据展示
//     * @return
//     */
//    public JSONArray getAllOrg(){
//        List<Companies> companiess = companiesMapper.selectList(null);
//        List<Roles> allRole = rolesService.getAllRole();
//        Map<Integer, List<Roles>> collect = allRole.stream().collect(Collectors.groupingBy(Roles::getCompanyId));
//        List<Companies> Companiess = new ArrayList<>();
//        for (Companies companies:companiess) {
//            if (companies.equals("") || companies == null){
//                System.out.println("这里导致的");
//            }
//            List<Roles> roles = collect.get(companies.getId());
//            if(roles == null){
//                //list集合为空
//                Companiess.add(companies);
//           }else {
//                companies.setRolesList(collect.get(companies.getId()));
//                Companiess.add(companies);
//            }
//        }
//        JSONArray jsonArray = new JSONArray();
//        for (Companies item : Companiess) {
//            jsonArray.add(item);
//        }
//        return jsonArray;
//    }
//
//
//    /**
//    * 添加部门的下拉框选项
//    * */
//    public Companies bycompany(String companyId){
//        LambdaQueryWrapper<Companies> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Companies::getId , companyId);
//        Companies companies = companiesMapper.selectOne(wrapper);
//        if (companies == null){
//            throw new BizException(BizCode.COMPANIES_ABSENT_ERROR);
//        }
//        Integer companiesId = companies.getId();
//        LambdaQueryWrapper<Roles> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Roles::getCompanyId , companiesId);
//
//        List<Roles> roless = rolesMapper.selectList(queryWrapper);
//        Map<String , Roles> map = new HashMap<>();
//        List<Roles> list = new ArrayList<>();
//        for (Roles roles : roless) {
//            //获取全部部门id
//            if (StringUtils.isNotBlank(roles.getParentId().toString())){
//                map.put(roles.getId().toString(), roles);
//            }
//        }
//
//        //实现树形结构
//        for (Roles roles : roless) {
//            //获取父id
//            String code = roles.getParentId().toString();
//            Roles parent = map.get(code);
//            //根据最高级组织中parentCode为0或者以parentCode为组织编码查不到组织的原理，把最高级组织对象add到list结构中
//            if (roles.getParentId() == 0){
//                list.add(roles);
//            }else {
//                Collection<Roles> children = parent.getRoles();
//                if (CollectionUtils.isEmpty(children)){
//                    parent.setRoles(new ArrayList<>());
//                }
//                parent.getRoles().add(roles);
//            }
//        }
//        companies.setRolesList(list);
//        return companies;
//    }
//
//
//
//    /**
//    * 根据部门id , 和公司id 去获取相应的权限和可视化菜单
//    * */
//    public PermissionMenusVO getPermissionMenus(String roleId){
//        PermissionMenusVO permissionMenusVO = new PermissionMenusVO();
//        LambdaQueryWrapper<RoleHasMenus> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(RoleHasMenus::getRoleId , roleId);
//        List<RoleHasMenus> roleHasMenus = roleHasMenusMapper.selectList(lambdaQueryWrapper);
//        if (roleHasMenus.isEmpty()){
//            throw new BizException(BizCode.MENUS_ABSENT_ERROR);
//        }
//        List<MenuVO> menuVOs = roleHasMenus.stream().map(roleHasMenus1 -> {
//            MenuVO menuVO = new MenuVO();
//            menuVO.setRoleId(roleHasMenus1.getRoleId());
//            menuVO.setId(roleHasMenus1.getMenuId());
//            LambdaQueryWrapper<Menus> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(Menus::getId, roleHasMenus1.getMenuId());
//            menuVO.setTitle(menusMapper.selectOne(wrapper).getTitle());
//            return menuVO;
//        }).collect(Collectors.toList());
//        LambdaQueryWrapper<RoleHasPermissions> permissionsLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        permissionsLambdaQueryWrapper.eq(RoleHasPermissions::getRoleId , roleId);
//        List<RoleHasPermissions> roleHasPermissions = roleHasPermissionsMapper.selectList(permissionsLambdaQueryWrapper);
//        if (roleHasPermissions.isEmpty()){
//            throw new BizException(BizCode.PERMISSION_ABSENT_ERROR);
//        }
//        List<PermissionVO> permissionVOs = roleHasPermissions.stream().map(roleHasPermissions1 -> {
//            PermissionVO permissionVO = new PermissionVO();
//            permissionVO.setRoleId(roleHasPermissions1.getRoleId());
//            permissionVO.setId(roleHasPermissions1.getPermissionId());
//            LambdaQueryWrapper<Permissions> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(Permissions::getId, roleHasPermissions1.getPermissionId());
//            permissionVO.setChineseName(permissionsMapper.selectOne(queryWrapper).getChineseName());
//            return permissionVO;
//        }).collect(Collectors.toList());
//        permissionMenusVO.setMenus(menuVOs);
//        permissionMenusVO.setPermissions(permissionVOs);
//        return permissionMenusVO;
//    }
//
//
//    /**
//    * 添加部门 , 开启事务，防止数据不全
//    * */
//    @Transactional(rollbackFor=Exception.class)
//    public Integer addRole(CreateRolesReq createRolesReq){
//        Date date = new Date(System.currentTimeMillis());
//        long time = date.getTime();
//        if (createRolesReq == null){
//            throw new BizException(BizCode.ORG_ABSENT_ERROR);
//        }
//        Roles roles = new Roles();
//        RoleHasMenusPermissions roleHasMenusPermissions = new RoleHasMenusPermissions();
//        Integer parentId = createRolesReq.getParentId();
//        roles.setParentId(parentId);
//        roles.setCompanyId(createRolesReq.getCompanyId());
//        roles.setChineseName(createRolesReq.getChineseName());
//        roles.setGuardName("测试");    //token去获取
//        roles.setCreatedAt(new Timestamp(time));
//        roles.setUpdatedAt(new Timestamp(time));
//        roles.setName(UUID.randomUUID().toString());
//        Integer insert = rolesMapper.insert(roles);
//        roleHasMenusPermissions.setRoleId(roles.getId().intValue());
//        roleHasMenusPermissions.setMenus(createRolesReq.getMenus());
//        roleHasMenusPermissions.setPermissions(createRolesReq.getPermissions());
//        roleHasMenusPermissionsMapper.insert(roleHasMenusPermissions);
//        return insert;
//
//    }
//
//
//    /**
//     * 修改部门 , 开启事务，防止数据不全
//     * */
//    @Transactional(rollbackFor=Exception.class)
//    public Integer updateRole(CreateRolesReq createRolesReq , Integer roleId){
//        Date date = new Date(System.currentTimeMillis());
//        long time = date.getTime();
//        if (createRolesReq == null){
//            throw new BizException(BizCode.ORG_ABSENT_ERROR);
//        }
//        LambdaQueryWrapper<Roles> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(Roles::getId , createRolesReq.getRoleId());
//        if (rolesMapper.selectOne(lambdaQueryWrapper) == null ){
//            throw new BizException(BizCode.NOT_HAVE_ROLE_ERROR);
//        }
//        Roles roles = new Roles();
//        RoleHasMenusPermissions roleHasMenusPermissions = new RoleHasMenusPermissions();
//        Integer parentId = createRolesReq.getParentId();
//        roles.setParentId(parentId);
//        roles.setCompanyId(createRolesReq.getCompanyId());
//        roles.setChineseName(createRolesReq.getChineseName());
//        roles.setGuardName("测试11");    //token去获取
//        roles.setUpdatedAt(new Timestamp(time));
//        LambdaQueryWrapper<Roles> rolesLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        Integer i = rolesMapper.update(roles , rolesLambdaQueryWrapper.eq(Roles::getId , roleId));
//        roleHasMenusPermissions.setRoleId(createRolesReq.getRoleId());
//        roleHasMenusPermissions.setMenus(createRolesReq.getMenus());
//        roleHasMenusPermissions.setPermissions(createRolesReq.getPermissions());
//        LambdaQueryWrapper<RoleHasMenusPermissions> permissionsLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        roleHasMenusPermissionsMapper.update(roleHasMenusPermissions , permissionsLambdaQueryWrapper.eq(RoleHasMenusPermissions::getRoleId , roleId));
//        return i;
//    }
//
//    /**
//     * 删除部门 , 开启事务，防止数据不全
//     * */
//    @Transactional(rollbackFor=Exception.class)
//    public Integer deleteRole(Integer roleId){
//        LambdaQueryWrapper<Roles> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(Roles::getId , roleId);
//        if (rolesMapper.selectOne(lambdaQueryWrapper) == null){
//            throw new BizException(BizCode.NOT_HAVE_ROLE_ERROR);
//        }
//        LambdaQueryWrapper<RoleHasMenusPermissions> permissionsLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        permissionsLambdaQueryWrapper.eq(RoleHasMenusPermissions::getRoleId , roleId);
//        if (roleHasMenusPermissionsMapper.selectOne(permissionsLambdaQueryWrapper) == null){
//            throw new BizException(BizCode.NOT_HAVE_ROLE_ERROR);
//        }
//        Integer deleteRole = rolesMapper.delete(lambdaQueryWrapper);
//        roleHasMenusPermissionsMapper.delete(permissionsLambdaQueryWrapper);
//        return deleteRole;
//    }
//
//
//    /**
//     * 通过公司id，获取部门数组
//     * */
//    public List<Long> getRoleList(String conpanyId){
//        LambdaQueryWrapper<Companies> companiesLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        companiesLambdaQueryWrapper.eq(Companies::getId , conpanyId);
//        if (companiesMapper.selectOne(companiesLambdaQueryWrapper) == null){
//            throw new BizException(BizCode.NOT_HAVE_COMPANY_ERROR);
//        }
//        LambdaQueryWrapper<Roles> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Roles::getCompanyId , conpanyId);
//        List<Long> roleList = rolesMapper.selectList(wrapper).stream().map(Roles::getId).collect(Collectors.toList());
//        if (roleList.isEmpty()){
//            throw new BizException(BizCode.COMPANY_NOT_HAVE_ROLES_ERROR);
//        }
//        return roleList;
//    }

    /**
     * 通过userId获取用户角色列表
     */
    public List<Role> getRoleListByUserId (Long userId) {
        //获取用户信息
        User user = btoUserService.getUserByUserId(userId);
        //判断用户是否存在
        if (user == null) {
            throw new BizException(BizCode.USER_ABSENT_ERROR);
        }
        return getRoleListByUser(user);
    }

    /**
     * 通过user获取用户角色列表
     */
    public List<Role> getRoleListByUser (User user) {
        List<String> roleIds = JsonToListUtils.convertJSONArrayToStringList(user.getRolesIds());
        return roleService.lambdaQuery().in(Role::getName, roleIds).list();
    }

    /**
     * 获取APP管理员列表
     */
    public List<UserVO.Role> getRoleList () {
        return roleService.lambdaQuery().ne(Role::getName, DBConstants.ROLE_SUPER_ADMIN)
                .list().stream().map(role -> {
                    UserVO.Role roleVO = new UserVO.Role();
                    roleVO.setName(role.getName()).setChineseName(role.getChineseName());
                    return roleVO;
                }).collect(Collectors.toList());
    }
}
